package xyz.xuminghai.javafx_learn.demo.roll_call;

import javafx.animation.AnimationTimer;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.text.Text;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 2023/12/11 2:30 星期一<br/>
 * 点名动画
 * @author xuMingHai
 */
public class RollCallAnimation extends AnimationTimer {

    private final ObservableList<Node> observableList;

    private final List<Text> nameList;

    private final SimpleBooleanProperty active = new SimpleBooleanProperty(this, "active");

    public RollCallAnimation(ObservableList<Node> observableList, List<Text> nameList) {
        this.observableList = observableList;
        this.nameList = nameList;
    }

    private void setRandomName() {
        int index = (int) (Math.random() * nameList.size());
        observableList.clear();
        observableList.add(nameList.get(index));
    }

    public SimpleBooleanProperty activeProperty() {
        return active;
    }

    private int handleStage1, handleStage2, handleStage3, handleStage4;

    @Override
    public void start() {
        super.start();
        if (!active.get()) {
            active.set(true);
            handleStage1 = (int)(Math.random() * (20 - 5)) + 5;
            handleStage2 = (int)(Math.random() * 7);
            handleStage3 = (int)(Math.random() * 4);
            handleStage4 = (int)(Math.random() * 2);
        }

    }

    @Override
    public void stop() {
        super.stop();
        if (active.get()) {
            active.set(false);
        }
    }

    private static final long STAGE1_PULSE = 100L;
    private static final long STAGE2_PULSE = 300L;
    private static final long STAGE3_PULSE = 500L;
    private static final long STAGE4_PULSE = 800L;

    // 上次运行的时间戳
    private long lastTimestamp;

    @Override
    public void handle(long now) {
        // 距离上次处理运行经过的时间
        long duration = TimeUnit.NANOSECONDS.toMillis(now - lastTimestamp);
        // 阶段1处理
        if (handleStage1 > 0 && duration >= STAGE1_PULSE) {
            setRandomName();
            handleStage1--;
            lastTimestamp = now;
        }
        else if (handleStage2 > 0 && duration >= STAGE2_PULSE) {
            setRandomName();
            handleStage2--;
            lastTimestamp = now;
        }
        else if (handleStage3 > 0 && duration >= STAGE3_PULSE) {
            setRandomName();
            handleStage3--;
            lastTimestamp = now;
        }
        else if (handleStage4 > 0 && duration >= STAGE4_PULSE) {
            setRandomName();
            handleStage4--;
            lastTimestamp = now;
        }
        // 所有阶段处理完毕
        else if ((handleStage1 + handleStage2 + handleStage3) == 0) {
            stop();
        }

    }


}
